<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div class="back-box" @click="gobackParent"
          ><img src="@/assets/images/back.svg" class="back-img" /><span>返回</span></div
        >
      </el-col>
      <el-col :span="8">
        <span
          ><span>计划组名称：</span><label>{{ props.receiveData.data.planName }}</label></span
        >
      </el-col>
    </el-row>
    <el-form v-show="state.showSearch" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="计划名称" prop="cPlanName">
        <el-input v-model.trim="queryParams.cPlanName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="投放时间" prop="planTime">
        <el-date-picker
          style="width: 360px"
          v-model="queryParams.planTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
        />
      </el-form-item>
      <el-form-item label="计划状态" prop="status">
        <el-select
          v-model="queryParams.status"
          clearable
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in props.devoteStatusOptions"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['devote:comboPlan:add']"
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增投放餐品</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList">
      <el-table-column
        label="计划编号"
        align="center"
        prop="cplanId"
        min-width="130"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="计划名称"
        align="center"
        prop="cplanName"
        min-width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        min-width="120"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          {{ formatDate(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        min-width="120"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          {{ formatDate(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        min-width="120"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="计划状态"
        align="center"
        prop="status"
        min-width="100"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <label :style="{ color: getStatusColor(scope.row.status) }"
            >• {{ getStatusText(scope.row.status) }}</label
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="140">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <el-button
              v-hasPermi="['devote:comboPlan:edit']"
              link
              type="primary"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-dropdown size="small" @command="handleAction($event, scope.row)">
              <span class="el-dropdown-link" @click.stop>
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="offShelf"
                    ><span v-hasPermi="['devote:comboPlan:offShelf']"
                      >商品下架</span
                    ></el-dropdown-item
                  >
                  <div v-show="scope.row.status === 'AwaitStart'">
                    <el-dropdown-item command="devote"
                      ><span v-hasPermi="['devote:comboPlan:putIn']">投放</span></el-dropdown-item
                    >
                  </div>
                  <div v-show="scope.row.status !== 'Invalidated'">
                    <el-dropdown-item command="lapse"
                      ><span v-hasPermi="['devote:comboPlan:lapse']">失效</span></el-dropdown-item
                    >
                  </div>
                  <el-dropdown-item command="copy"
                    ><span v-hasPermi="['devote:comboPlan:copy']">复制</span></el-dropdown-item
                  >
                  <el-dropdown-item command="print"
                    ><span v-hasPermi="['devote:comboPlan:print']">打印</span></el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList()"
    />

    <operate
      ref="operateRef"
      :operType="state.operType"
      :planId="props.receiveData.data.planId"
      :adTypeOptions="adTypeOptions"
      @updateList="getList()"
    />
    <comboPlanPrint ref="comboPlanPrintRef" />
    <selectOffShelfCombo ref="selectoffshelfcomboRef" @updateList="getList()" />
  </div>
</template>

<script setup name="advertmanage">
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/index'
import { getComboPlanList, changeComboPlanStatus } from '@/api/devote'
import { reactive } from 'vue'
import operate from './templates/operate.vue'
import comboPlanPrint from './templates/comboPlanPrint.vue'
import selectOffShelfCombo from './templates/selectoffshelfcombo.vue'

const props = defineProps({
  receiveData: {
    type: Object,
    default: () => {}
  },
  devoteStatusOptions: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['goback', 'cancel'])
const gobackParent = () => {
  emit('goback')
}
const cancelParent = () => {
  emit('cancel')
}

const queryRef = ref(null)
const { proxy } = getCurrentInstance()

const adTypeOptions = ref([])
const state = reactive({
  currentId: null,
  actionType: '',
  dialogTitle: '',
  showSearch: true,
  total: 1,
  loading: false,
  operType: '',
  detailId: '',
  data: {}
})
const groupPlandTime = ref(null)
const queryParams = ref({
  planId: null,
  pageNum: 1,
  pageSize: 10,
  cPlanName: null,
  planTime: null,
  start_time: null,
  end_time: null,
  status: null
})
const tableList = ref([])

function handleSearch(confirm) {
  !confirm && queryRef.value.resetFields()
  getList(true)
}

async function getList(refresh) {
  state.loading = true
  if (refresh) queryParams.value.pageNum = 1

  let { planTime = [], ...obj } = queryParams.value
  if (planTime && planTime.length) {
    obj.start_time = getTimestamp(planTime[0]) || ''
    obj.end_time = getTimestamp(planTime[1]) || ''
  }

  try {
    const res = await getComboPlanList(obj)
    tableList.value = res?.data.rows || []
    state.total = res?.data?.total || 0
  } finally {
    state.loading = false
  }
}

/**table Action */
function handleAdd() {
  state.operType = 'add'
  state.data = {}
  console.log('props.receiveData.cityName', props.receiveData.cityName)
  proxy.$refs['operateRef'].show(
    'add',
    { cityName: props.receiveData.cityName },
    groupPlanLaunchTime.value
  )
}
function handleEdit(row) {
  state.operType = 'edit'
  row.cityName = props.receiveData.cityName
  proxy.$refs['operateRef'].show('edit', row, groupPlanLaunchTime.value)
}

function handleAction(command, row) {
  if (command === 'copy') {
    //复制
    state.operType = 'add'
    proxy.$refs['operateRef'].show('copy', row, groupPlanLaunchTime.value)
  } else if (command === 'devote' || command === 'lapse') {
    //投放，失效
    const statusParams = command === 'devote' ? 'Ongoing' : 'Invalidated'
    const params = {
      status: statusParams,
      cPlanId: row.cplanId
    }
    changeComboPlanStatus(params).then((res) => {
      getList()
      ElMessage.success('操作成功')
    })
  } else if (command === 'offShelf') {
    // 下架
    proxy.$refs['selectoffshelfcomboRef'].handleAddFileColumn(row)
  } else {
    proxy.$refs['comboPlanPrintRef'].handlePrint(row)
  }
}
function getStatusText(status) {
  const match = props.devoteStatusOptions.find((option) => option.value == status)
  return match ? match.name : '未知'
}
function getStatusColor(status) {
  if (getStatusText(status) == '待投放') {
    return '#409eff'
  } else if (getStatusText(status) == '进行中') {
    return '#67c23a'
  } else {
    return '#f0864d'
  }
}
function getTimestamp(dateStr) {
  return new Date(dateStr).getTime()
}

const groupOperType = ref('view')
const groupPlanLaunchTime = ref({
  startTime: null,
  endTime: null
})
/**init */
function init() {
  groupOperType.value = props.receiveData.operType
  queryParams.value.planId = props.receiveData.data.planId
  groupPlanLaunchTime.value.startTime = props.receiveData.data.startTime
  groupPlanLaunchTime.value.endTime = props.receiveData.data.endTime

  getList()
}

init()
</script>

<style lang="scss" scoped>
.back-box {
  .back-img {
    width: 20px;
    height: 20px;
  }
  display: flex;
  align-items: center;
  font-size: 14px;
  cursor: pointer;
  margin-right: 10px;
}
</style>
